<template>
  <el-dialog v-model="dialogVisible" append-to-body :title="dialogTitle" width="540">
    <div class="form-box">
      <el-form v-if="dialogVisible" label-width="100px" :model="formObj" ref="formRef" :rules="rules" size="large">
        <el-form-item label="用户ID" prop="user_id">
          <el-input v-model="formObj.user_id" type="text" disabled autocomplete="off" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="代理类型" prop="proxy_type">
          <el-select v-model="formObj.proxy_type" filterable clearable placeholder="请选择代理类型" disabled>
            <el-option label="动态类型" :value="1" />
            <el-option label="静态类型" :value="2" />
          </el-select>
        </el-form-item>
        <div v-if="formObj.proxy_type == 1" key="proxy_type-1">
          <el-form-item label="套餐类型" prop="goods_info" key="goods_info-1">
            <el-select v-model="formObj.goods_info" filterable clearable placeholder="请选择套餐类型">
              <el-option label="体验版-1GB-$5" value="体验版-1GB-$5" />
              <el-option label="新用户-8+2GB-$40" value="新用户-8+2GB-$40" />
              <el-option label="最受欢迎-75+25GB-$300" value="最受欢迎-75+25GB-$300" />
              <el-option label="商业-300GB-$750" value="商业-300GB-$750" />
              <el-option label="企划级-1000GB-$2000" value="企划级-1000GB-$2000" />
              <el-option label="赠送体验200MB套餐" value="赠送体验200MB套餐" />
            </el-select>
          </el-form-item>
          <el-form-item label="充值流量" prop="quantity" key="quantity-1">
            <el-input v-model.number="formObj.quantity" type="number" autocomplete="off" placeholder="请输入充值流量">
              <template #prepend>G</template>
            </el-input>
          </el-form-item>
        </div>
        <div v-else-if="formObj.proxy_type == 2" key="proxy_type-2">
          <el-form-item label="国家/地区" prop="country_code" key="country_code">
            <el-select
              v-model="formObj.country_code"
              :disabled="formObj.type == 'staticRenewRecharge'"
              filterable
              clearable
              placeholder="请选择国家和地区"
              class="full-width"
              @change="onCountryChange"
            >
              <el-option v-for="item in countryList" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
          </el-form-item>
          <el-form-item label="IP类型" prop="line_type" key="line_type-2">
            <el-select
              v-model="formObj.line_type"
              :disabled="formObj.type == 'staticRenewRecharge'"
              filterable
              clearable
              placeholder="请选择IP类型"
              @change="onCalculatePrice"
            >
              <el-option label="标准" value="2" />
              <el-option label="高级" value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="业务用途" prop="business" key="business-2">
            <el-select
              v-model="formObj.business"
              :disabled="formObj.type == 'staticRenewRecharge'"
              filterable
              clearable
              placeholder="请选择业务用途"
              class="full-width"
              @change="onBusinessChange"
            >
              <el-option v-for="item in businessList" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item label="选择套餐" prop="days" key="days-2">
            <el-select v-model="formObj.days" filterable clearable placeholder="请选择套餐" @change="onCalculatePrice">
              <el-option label="30天" value="30" />
              <el-option label="60天" value="60" />
              <el-option label="90天" value="90" />
              <el-option label="360天" value="360" />
            </el-select>
          </el-form-item>
          <el-form-item label="购买数量" prop="quantity" key="quantity-2" @change="onCalculatePrice">
            <el-input
              v-model.number="formObj.quantity"
              :disabled="formObj.type == 'staticRenewRecharge'"
              type="number"
              :min="1"
              autocomplete="off"
              placeholder="请输入购买数量"
            />
          </el-form-item>
        </div>
        <el-form-item label="支付金额" prop="amount" key="amount">
          <el-input v-model.number="formObj.amount" type="number" autocomplete="off" placeholder="请输入支付金额">
            <template #prepend>$</template>
          </el-input>
        </el-form-item>
        <el-form-item label="支付方式" prop="pay_way" key="pay_way">
          <el-select v-model="formObj.pay_way" filterable clearable placeholder="请选择支付方式">
            <el-option label="USDT" value="USDT" />
            <el-option label="支付宝" value="alipay" />
            <el-option label="信用卡" value="card" />
            <el-option label="其它" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注说明" prop="remark" key="remark">
          <el-input v-model="formObj.remark" type="textarea" autocomplete="off" placeholder="请输入备注说明" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div style="text-align: center">
        <el-button size="large" @click="onClose()">取消</el-button>
        <el-button type="primary" size="large" :disabled="loading" :loading="loading" @click="onSubmit(formRef)">提交</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
  import { ref, watch } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { useUserStore } from '@/store/modules/user';
  import { manageRechargeApi, manageStaticRechargeApi, manageStaticRenewRechargeApi, staticRegionApi, businessApi } from '@/api/index';
  import type { FormInstance, FormRules } from 'element-plus';
  import { calculatePrice } from '@/utils/index';

  const route = useRoute();
  const router = useRouter();
  const userStore = useUserStore();

  const getUserInfo = computed(() => {
    let userInfo = userStore.getUserInfo || {};
    return userInfo;
  });

  const emits = defineEmits<{
    (event: 'confirm'): void;
  }>();

  const loading = ref(false);
  const formRef = ref<FormInstance>();
  const formObj = reactive({
    type: '',
    user_id: '',
    order_nu: '',
    proxy_type: 1,
    goods_info: '',
    quantity: 0,
    country_code: '',
    country_code_str: '',
    line_type: '',
    line_type_str: '',
    business: '',
    business_str: '',
    days: '',
    amount: 0,
    pay_way: '',
    remark: '',
  });

  const dialogTitle = ref('');
  const dialogVisible = ref(false);

  const rules = reactive<FormRules>({
    user_id: [{ required: true, message: '请输入用户ID', trigger: 'change' }],
    proxy_type: [{ required: true, message: '请选择代理类型', trigger: 'change' }],
    goods_info: [{ required: true, message: '请输入套餐类型', trigger: 'change' }],
    quantity: [{ required: true, message: '请输入充值流量', trigger: 'change' }],
    amount: [{ required: true, message: '请输入支付金额', trigger: 'change' }],
    pay_way: [{ required: true, message: '请选择支付方式', trigger: 'blur' }],
    // remark: [{ required: true, message: '请输入备注说明', trigger: 'blur' }],
    country_code: [{ required: true, message: '请选择国家和地区', trigger: 'change' }],
    line_type: [{ required: true, message: '请选择IP类型', trigger: 'change' }],
    business: [{ required: true, message: '请选择业务用途', trigger: 'change' }],
    days: [{ required: true, message: '请选择套餐类型', trigger: 'change' }],
  });

  const countryList = ref([]);
  const businessList = ref([]);

  const onCountryChange = (val) => {
    let obj = countryList.value.find((v) => v.code == val);
    formObj.country_code_str = obj?.name || '';
  };

  const onLineTypeChange = (val) => {
    if (val == 2) {
      formObj.line_type_str = '标准';
    } else if (val == 3) {
      formObj.line_type_str = '高级';
    }
  };

  const onBusinessChange = (val) => {
    let str = businessList.value.find((v) => v == val);
    formObj.business_str = str || '';
  };

  const onCalculatePrice = () => {
    if (formObj.proxy_type == 2) {
      formObj.amount = calculatePrice(formObj.line_type, formObj.days, formObj.quantity);
    }
  };

  const getRegion = async (type) => {
    staticRegionApi({})
      .then((res) => {
        if (res.data) {
          if (type == 'country') {
            countryList.value = res.data;
            onCountryChange(formObj.country_code);
          }
        }
      })
      .catch((err) => {
        console.log('err', err);
        ElMessage.error(err.message);
      });
  };

  const getBusiness = async () => {
    businessApi({})
      .then((res) => {
        if (res.data) {
          businessList.value = res.data;
          onBusinessChange(formObj.business);
        }
      })
      .catch((err) => {
        console.log('err', err);
        ElMessage.error(err.message);
      });
  };

  const onReset = (data, type) => {
    formObj.user_id = type == 'staticRenewRecharge' ? data.user_id : data.id;
    formObj.type = type;
    formObj.proxy_type = type == 'recharge' ? 1 : 2;
    formObj.goods_info = data.goods_info || '';
    formObj.quantity = type == 'recharge' ? 0 : 1;
    formObj.amount = 0;
    formObj.pay_way = 'alipay';
    formObj.remark = data.remark || '';
    formObj.order_nu = data.order_nu || '';
    formObj.country_code = '';
    formObj.country_code_str = '';
    formObj.line_type = '2';
    formObj.line_type_str = '标准';
    formObj.business = '';
    formObj.business_str = '';
    formObj.days = '30';
    if (type == 'staticRenewRecharge') {
      const extendObj = JSON.parse(data.extend || '{}');
      formObj.quantity = extendObj.quantity || 1;
      formObj.country_code = extendObj.country_code || '';
      formObj.country_code_str = extendObj.country_code_str || '';
      formObj.line_type = extendObj.line_type || '2';
      formObj.line_type_str = extendObj.line_type_str || '标准';
      formObj.business = extendObj.business || '';
      formObj.business_str = extendObj.business_str || '';
      formObj.days = extendObj.days || '30';
      onLineTypeChange(formObj.line_type);
    }
  };

  const onOpen = (data, type, title) => {
    dialogTitle.value = title;
    dialogVisible.value = true;
    onReset(data, type);
    onCalculatePrice();
    getRegion('country');
    getBusiness();
  };

  const onClose = () => {
    dialogTitle.value = '';
    dialogVisible.value = false;
  };

  const onSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
      if (valid) {
        onSubmitFn();
      }
    });
  };

  const onSubmitFn = async () => {
    if (loading.value) return false;
    loading.value = true;
    let Fn = <any>null;
    if (formObj.type == 'recharge') {
      Fn = manageRechargeApi;
    } else if (formObj.type == 'staticRecharge') {
      Fn = manageStaticRechargeApi;
    } else if (formObj.type == 'staticRenewRecharge') {
      Fn = manageStaticRenewRechargeApi;
    }
    Fn(formObj)
      .then((res) => {
        loading.value = false;
        if (res.errcode == 0) {
          ElMessage.success(res.message || res.errmsg);
          emits('confirm', formObj.proxy_type);
          onClose();
        } else {
          ElMessage.error(res.message || res.errmsg);
        }
      })
      .catch((err) => {
        console.log('err', err);
        loading.value = false;
        ElMessage.error(err.message);
      });
  };

  defineExpose({
    onOpen,
  });

  onMounted(() => {});
</script>

<style scoped lang="scss">
  .form-box {
    padding: 10px 20px 0 0;
  }
</style>
